<?php

namespace app\base\controller;

use app\admin\model\Classes;
use app\common\controller\AdminBase;
use app\base\model as modelBase;
use think\Cache;
use think\Exception;
use think\Loader;
use think\Request;

class Teacher extends AdminBase {
  private $model, $modelRole;

  public function __construct() {
    parent::__construct();
    $this->model = new modelBase\User();
    $this->modelRole = new modelBase\Role();
  }

  public function _initialize() {
    parent::_initialize(); // TODO: Change the autogenerated stub
  }

  public function index() {
    $search = input('search/a', []);
    $map = ['role_id' => 2];
    if (isset($search['username'])) {
      $searchName = $search['username'];
      if (is_numeric($searchName)) {
        $map['u.username'] = ['like',
                              "%{$searchName}%"];
      } else {
        $map['u.realname'] = ['like',
                              "%{$searchName}%"];
      }
    }
    $rows = $this->model->alias('u')
      ->where($map)
      ->order('u.id ASC')
      ->field('u.id,u.username,u.realname,u.class_id,u.status,u.role_id')
      ->paginate();

    return view('', [
      'rows'   => $rows,
      'search' => $search,
    ]);

  }

  public function add() {
    return self::edit();
  }

  public function edit() {
    $id = input('id/d', 0, 'abs');
    if (!request()->isPost()) {
      $modelClass = new Classes();
      $row = ($id > 0) ? $this->model->find($id) : [];

      //
      return view('edit', [
        'row'      => $row,
        'id'       => $id,
        'disabled' => $id > 0 ? 'disabled="disabled"' : '',
      ]);
    } else {
      $form = input('form/a', NULL);
      $validate = new \app\base\validate\User();
      $result = $validate->scene($id > 0 ? 'edit' : 'add')->check($form);
      if (TRUE !== $result) {
        $this->error($validate->getError());
      }
      $form['status'] = isset($form['status']) ? $form['status'] : 0;

      $r = $id > 0 ? $this->model->editUser($form, $id) : $this->model->addUser($form);

      if ($r !== TRUE) {
        $this->error(lang('error') . $r);
      }
      $this->success(lang('success'), url('index'));
    }
  }

  public function user_select_layer() {
    $map = ['u.status' => 1];
    $data = [];
    $users = $this->model
      ->alias('u')
      ->where($map)
      ->join('__BASE_DEPARTMENT__ d', 'u.department_id=d.id', 'left')
      ->column('u.realname,u.department_id,d.title', 'u.id');
    foreach ($users as $uid => $user) {
      $data[ $user['department_id'] ][ $uid ]['realname'] = $user['realname'];
    }

    $deptAll = $this->modelDept->column('parent_id,title', 'id');
    $this->assign('users', $users);
    $this->assign('data', $data);
    $this->assign('deptSelect', $this->modelDept->select());

    $this->assign('dept_all', $deptAll);

    return view('', ['userJson' => json_encode($data)]);
  }

  public function password() {
    if (!request()->isPost()) {
      return view();
    }
    $form = input('form/a', NULL, 'trim');
    if ($form['password'] != $form['password2'])
      $this->error('两次密码不相同');
    $data['salt'] = rand(100000, 999999);
    $data['password'] = $this->model->createPassword($form['password'], $data['salt']);
    try {
      $this->model->save($data, ['id' => $this->uid]);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    $this->success(lang('success'));

  }

  public function resetpw() {
    $id = input('id/d', 0, 'abs');
    $row = $this->model->find($id);
    if (!$row) $this->error(lang('data empty'));
    $defPw = config('system')['default_password'];
    $pw = $this->model->createPassword($defPw, $row['salt']);
    $data = ['password' => $pw];
    try {
      $this->model->save($data, ['id' => $id]);
    } catch (Exception $e) {
      $this->error($e->getMessage());
    }
    $this->success('密码已经重置为' . $defPw);
  }
}
